//
//  CancelViewController.m
//  dangdang
//
//  Created by air on 16/1/27.
//  Copyright © 2016年 luweijie. All rights reserved.
//

#import "CancelViewController.h"
#import "CancelTableViewCell.h"
#import "DetailsViewController.h"
#import "MJRefresh.h"
#import "OrderObject.h"

@interface CancelViewController ()

@property (nonatomic, strong) UIRefreshControl * refresh;
@property (nonatomic, strong) NSArray * orderCountArray;
@property (nonatomic, strong) NSMutableArray * orderDetailsArray;
@property (nonatomic, strong) NSDictionary * dic;
@property (nonatomic) BOOL pullDown;
@property (nonatomic) BOOL pullUp;
@property (nonatomic) NSInteger page;

@end

@implementation CancelViewController

- (instancetype)init {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"CancelViewController" bundle:nil];
    self = [sb instantiateViewControllerWithIdentifier:@"CancelViewController"];
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _cancelTableView.rowHeight = UITableViewAutomaticDimension;
    _cancelTableView.estimatedRowHeight = 44.0;
    _cancelTableView.backgroundColor = [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:239.0/255.0 alpha:1.0];
    
    [self initialization];
    
    [self connection];
    
    [self setupRefresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initialization{
    _orderDetailsArray = [NSMutableArray new];
    _page = 1;
    
    _pullDown = NO;
    _pullUp = NO;
}

- (void)connection{
    NSString * token = userObject.accessToken;
    NSString * userIDString = userObject.userID;
    NSString * pageString = @"0";
    NSString * pageSizeString = @"30";
    NSString * statusString = @"4";
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:token forKey:@"token"];
    [params setObject:userIDString forKey:@"uid"];
    [params setObject:pageString forKey:@"page"];
    [params setObject:pageSizeString forKey:@"pagesize"];
    [params setObject:statusString forKey:@"status"];
    
    [self postRequestWithMethodName:@"order/get_order_list" andParams:params andSender:nil];
}

//上拉刷新
- (void)setupFooterRefresh{
    _pullUp = YES;
    
    __unsafe_unretained __typeof(self) weakSelf = self;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.cancelTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMoreData];
    }];
}

#pragma mark 上拉加载更多数据
- (void)loadMoreData
{
    _pullUp = YES;
    
    NSString * token = userObject.accessToken;
    NSString * userIDString = userObject.userID;
    NSString * pageString = [NSString stringWithFormat:@"%ld", (long)_page];
    NSString * pageSizeString = @"30";
    NSString * statusString = @"4";
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:token forKey:@"token"];
    [params setObject:userIDString forKey:@"uid"];
    [params setObject:pageString forKey:@"page"];
    [params setObject:pageSizeString forKey:@"pagesize"];
    [params setObject:statusString forKey:@"status"];
    
    [self postRequestWithMethodName:@"order/get_order_list" andParams:params andSender:nil];
}

/**
 *  集成下拉刷新
 */
-(void)setupRefresh
{
    self.refresh = [[UIRefreshControl alloc]init];
    //刷新图形颜色
    self.refresh.tintColor = [UIColor lightGrayColor];
    //刷新的标题
    self.refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
    
    [self.refresh addTarget:self action:@selector(refreshStateChange:) forControlEvents:UIControlEventValueChanged];
    
    [self.cancelTableView addSubview:self.refresh];
}

/**
 *  UIRefreshControl进入刷新状态：加载最新的数据
 */
-(void)refreshStateChange:(UIRefreshControl *)control
{
    if (control.refreshing) {
        _pullDown = YES;
        _page = 1;
        
        control.attributedTitle = [[NSAttributedString alloc]initWithString:@"正在刷新"];
        
        NSString * token = userObject.accessToken;
        NSString * userIDString = userObject.userID;
        NSString * pageString = @"0";
        NSString * pageSizeString = @"30";
        NSString * statusString = @"4";
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:userIDString forKey:@"uid"];
        [params setObject:pageString forKey:@"page"];
        [params setObject:pageSizeString forKey:@"pagesize"];
        [params setObject:statusString forKey:@"status"];
        
        [self postRequestWithMethodName:@"order/get_order_list" andParams:params andSender:nil];
    }
}

#pragma mark UITableViewDataSource && Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _orderDetailsArray.count;
//    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CancelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cancelCell" forIndexPath:indexPath];

    cell.layer.borderWidth = 1;
    cell.layer.borderColor = [[[UIColor lightGrayColor] colorWithAlphaComponent:0.5] CGColor];
    cell.layer.cornerRadius = 10;
    
    OrderObject * orderObject = [[OrderObject alloc] init];
    orderObject = _orderDetailsArray[indexPath.section];
    if ([orderObject.item_buy_location_name isEqualToString:@"<null>"]) {
        cell.buyLocationLabel.text = @"不限";
    }else{
        cell.buyLocationLabel.text = orderObject.item_buy_location_name;
    }
    cell.sendLocationLabel.text = orderObject.location_name;
    cell.feeLabel.text = [NSString stringWithFormat:@"%@元", orderObject.item_price];
    cell.timeLabel.text = orderObject.order_time;
    //    cell.secondLabel.text = [NSString stringWithFormat:@"%@千米", orderObject.distance];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailsViewController * detailsboardVC = [[UIStoryboard storyboardWithName:@"DetailsViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"DetailsViewController"];
    
    detailsboardVC.titleString = @"已取消";
    OrderObject * orderObject = [[OrderObject alloc] init];
    orderObject = _orderDetailsArray[indexPath.section];
    userObject.ordID = orderObject.order_id;
    
    [self.navigationController pushViewController:detailsboardVC animated:YES];
}

//网络连接返回数据
- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender{
    
    NSString * urlString = [NSString stringWithFormat:@"%@", task.currentRequest.URL];
    
    if ([result isKindOfClass:[NSDictionary class]]) {
        NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
        if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"order/get_order_list"]]){
            if ([code isEqualToString:@"0"]) {
                NSArray * arrayCount = [result objectForKey:@"retmsg"];
                if (arrayCount.count == 0 && _pullDown == YES) {
                    self.refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"全部加载完毕"];
                    [self.refresh endRefreshing];
                    _pullDown = NO;
                }else if (!(arrayCount.count == 0) && _pullDown == YES){
                    _orderDetailsArray = [NSMutableArray new];
                    _orderCountArray = [result objectForKey:@"retmsg"];
                    
                    for (int i = 0; i < _orderCountArray.count; i ++) {
                        OrderObject * orderObject = [[OrderObject alloc] init];
                        _dic = _orderCountArray[i];
                        orderObject.city_id = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"city_id"]];
                        orderObject.distance = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"distance"]];
                        orderObject.exp_fee = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"exp_fee"]];
                        orderObject.exp_uid = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"exp_uid"]];
                        orderObject.is_commented = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"is_commented"]];
                        orderObject.item_name = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"item_name"]];
                        orderObject.item_price = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"item_price"]];
                        orderObject.item_weight = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"item_weight"]];
                        orderObject.location_lat = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"location_lat"]];
                        orderObject.location_lng = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"location_lng"]];
                        orderObject.location_name = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"location_name"]];
                        orderObject.order_id = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"order_id"]];
                        orderObject.order_serial = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"order_serial"]];
                        orderObject.order_time = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"order_time"]];
                        orderObject.pay_serial = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"pay_serial"]];
                        orderObject.pay_status = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"pay_status"]];
                        orderObject.pay_type = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"pay_type"]];
                        orderObject.reach_time = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"reach_time"]];
                        orderObject.reach_time_final = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"reach_time_final"]];
                        orderObject.remark = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"remark"]];
                        orderObject.status = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"status"]];
                        orderObject.uid = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"uid"]];
                        orderObject.item_buy_location_name = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"item_buy_location_name"]];
                        
                        [_orderDetailsArray addObject:orderObject];
                    }
                    [self.refresh endRefreshing];
                    
                    [_cancelTableView reloadData];
                    
                    [self setupFooterRefresh];
                    
                    _pullDown = NO;
                }else if (!(arrayCount.count == 0) && _pullUp == YES){
                    _orderCountArray = [result objectForKey:@"retmsg"];
                    for (int i = 0; i < _orderCountArray.count; i ++) {
                        OrderObject * orderObject = [[OrderObject alloc] init];
                        _dic = _orderCountArray[i];
                        orderObject.city_id = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"city_id"]];
                        orderObject.distance = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"distance"]];
                        orderObject.exp_fee = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"exp_fee"]];
                        orderObject.exp_uid = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"exp_uid"]];
                        orderObject.is_commented = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"is_commented"]];
                        orderObject.item_name = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"item_name"]];
                        orderObject.item_price = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"item_price"]];
                        orderObject.item_weight = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"item_weight"]];
                        orderObject.location_lat = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"location_lat"]];
                        orderObject.location_lng = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"location_lng"]];
                        orderObject.location_name = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"location_name"]];
                        orderObject.order_id = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"order_id"]];
                        orderObject.order_serial = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"order_serial"]];
                        orderObject.order_time = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"order_time"]];
                        orderObject.pay_serial = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"pay_serial"]];
                        orderObject.pay_status = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"pay_status"]];
                        orderObject.pay_type = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"pay_type"]];
                        orderObject.reach_time = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"reach_time"]];
                        orderObject.reach_time_final = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"reach_time_final"]];
                        orderObject.remark = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"remark"]];
                        orderObject.status = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"status"]];
                        orderObject.uid = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"uid"]];
                        orderObject.item_buy_location_name = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"item_buy_location_name"]];
                        
                        [_orderDetailsArray addObject:orderObject];
                    }
                    _page ++;
                    [_cancelTableView.mj_footer endRefreshing];
                    [_cancelTableView reloadData];
                    
                    _pullUp = NO;
                }else if (arrayCount.count == 0 && _pullUp == YES){
                    [_cancelTableView.mj_footer endRefreshingWithNoMoreData];
                    
                    _pullUp = NO;
                }else if (!(arrayCount.count == 0)){
                    _orderCountArray = [result objectForKey:@"retmsg"];
                    for (int i = 0; i < _orderCountArray.count; i ++) {
                        OrderObject * orderObject = [[OrderObject alloc] init];
                        _dic = _orderCountArray[i];
                        orderObject.city_id = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"city_id"]];
                        orderObject.distance = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"distance"]];
                        orderObject.exp_fee = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"exp_fee"]];
                        orderObject.exp_uid = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"exp_uid"]];
                        orderObject.is_commented = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"is_commented"]];
                        orderObject.item_name = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"item_name"]];
                        orderObject.item_price = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"item_price"]];
                        orderObject.item_weight = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"item_weight"]];
                        orderObject.location_lat = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"location_lat"]];
                        orderObject.location_lng = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"location_lng"]];
                        orderObject.location_name = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"location_name"]];
                        orderObject.order_id = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"order_id"]];
                        orderObject.order_serial = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"order_serial"]];
                        orderObject.order_time = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"order_time"]];
                        orderObject.pay_serial = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"pay_serial"]];
                        orderObject.pay_status = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"pay_status"]];
                        orderObject.pay_type = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"pay_type"]];
                        orderObject.reach_time = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"reach_time"]];
                        orderObject.reach_time_final = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"reach_time_final"]];
                        orderObject.remark = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"remark"]];
                        orderObject.status = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"status"]];
                        orderObject.uid = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"uid"]];
                        orderObject.item_buy_location_name = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"item_buy_location_name"]];
                        
                        [_orderDetailsArray addObject:orderObject];
                    }
                    [_cancelTableView reloadData];
                    
                    [self setupFooterRefresh];
                }
            }else{
                if (_pullUp == YES) {
                    [_cancelTableView.mj_footer endRefreshing];
                }else if (_pullDown == YES){
                    [self.refresh endRefreshing];
                }
            }
        }
    }
}

- (void)requestFailureWithNSURLSessionTask:(NSURLSessionTask *)task error:(NSError *)error sender:(id)sender
{
    if (_pullUp == YES) {
        [_cancelTableView.mj_footer endRefreshing];
    }else if (_pullDown == YES){
        [self.refresh endRefreshing];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
